package com.mender.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.mender.common.constant.JwtClaimsConstant;
import com.mender.common.properties.JwtProperties;
import com.mender.common.utils.JwtUtil;
import com.mender.gateway.config.AuthProperties;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class JwtTokenUserGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtProperties jwtProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 如果是 user 接口才进
        if (!request.getPath().toString().startsWith("/user")) {
            return chain.filter(exchange);
        }

        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst(jwtProperties.getUserTokenName());
        ServerHttpResponse response = exchange.getResponse();

        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            exchange = exchange.mutate()
                    .request(builder -> builder.header("user-info", userId.toString()))
                    .build();
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 1; // 比 admin 滞后一点
    }
}
